package com.longxi.tianjintianbao.ui.presenter.repair;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.SelectPersonnelListener;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.ui.adapter.multitype.LabelViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.PersonnelViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.repair.IPersonnelAtView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 选择人员进行派单
 */

public class PersonnelAtPresenter extends BasePresenter<IPersonnelAtView> {

//    public static String DEPTID = "DEPTID";//部门内部编码
//    public static String MULTI_SELECTION = "MULTI_SELECTION";//是否可多选
    private MultiTypeAdapter adapter;
    private Items items;
    List<Personnel> personnelList = new ArrayList<>();
    List<Personnel> personnelListIntent = new ArrayList<>();//回传值用
    List<Personnel> personnelListGL = new ArrayList<>();//传过来的值
    private String deptid = "";//部门内部编码
    private boolean multiSelection = false;//是否可多选 默认不可

    public PersonnelAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        deptid = intent.getStringExtra(AppConst.DEPTID);
        multiSelection = intent.getBooleanExtra(AppConst.MULTI_SELECTION, false);
        personnelListGL = (List<Personnel>) intent.getSerializableExtra(AppConst.PERSONNEL_LISTINTENT);
        mContext.setTitle("人员列表");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
        mContext.setTvRight("确定");
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */

            SelectPersonnelListener selectAreaListener = new SelectPersonnelListener() {

                @Override
                public void onSelectPersonnel(Personnel personnel, int position) {
                    if(multiSelection){
                        multiSelection(personnel, position);
                    }else{
                        singleElection(personnel, position);
                    }
                }
            };
            adapter.register(String.class, new LabelViewBinder());
            adapter.register(Personnel.class, new PersonnelViewBinder(selectAreaListener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void getPersonnel(){

        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("deptid", deptid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getPersonnel(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Personnel>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<Personnel> result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    mContext.showNoData();
                    return;
                }
                personnelList = removeDuplicate(result.getData());

                if(personnelListGL != null && personnelListGL.size() > 0){
                    for (int i = 0; i < personnelListGL.size(); i++) {
                        for (int j = 0; j < personnelList.size(); j++) {
                            if(personnelListGL.get(i).getUserid().equals(personnelList.get(j).getUserid())){
                                personnelList.get(j).setSelect(true);
                                personnelListIntent.add(personnelList.get(j));
                            }
                        }
                    }
                }

                groupBys();
            }
        });
    }

    /**
     * 派单
     */
    public void hdPersonnel(){
        if(personnelListIntent.size() == 0) {
            MyUtils.showToast("请指选择人员");
        }
        Intent intent = new Intent();
        intent.putExtra(AppConst.PERSONNEL_LISTINTENT,  (Serializable) personnelListIntent);
        mContext.setResult(Activity.RESULT_OK, intent);
        mContext.finish();
    }

    /**
     * 单选
     */
    public void singleElection(Personnel personnel, int position){
        for (int i = 0; i < personnelList.size(); i++) {
            Personnel per = personnelList.get(i);
            if(personnel.getUserid().equals(per.getUserid())){
                if(per.isSelect()){
                    personnelListIntent.clear();
                    per.setSelect(false);
                }else{
                    personnelListIntent.clear();
                    personnelListIntent.add(personnel);
                    per.setSelect(true);
                }
            }else{
                per.setSelect(false);
            }
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 多选
     */
    public void multiSelection(Personnel personnel, int position){
        if(personnel.isSelect()){
            personnelListIntent.remove(personnel);
            personnel.setSelect(false);
        }else{
            personnelListIntent.add(personnel);
            personnel.setSelect(true);
        }
        adapter.notifyItemChanged(position);
    }

    /**
     * 员工数据分组
     */
    public void groupBys() {
        Map map = new HashMap();
        String key_str = "";
        List<Personnel> value_list;

        /*** 将list分组，存入map ***/
        for (Personnel personnel : personnelList) {
            key_str = personnel.getDept();
            value_list = new ArrayList<>();

            if (key_str != null) {
                if (map.containsKey(key_str)) {
                    value_list = (List<Personnel>) map.get(key_str);
                }
                value_list.add(personnel);
                map.put(key_str, value_list);

            }
        }
        items = new Items();
        for(Object key : map.keySet()){
            items.add(key.toString());
            List<Personnel> personnels = (List<Personnel>) map.get(key);
            items.addAll(personnels);
        }
        adapter.setItems(items);
        adapter.notifyDataSetChanged();
        mContext.hideLoading();
    }

    /**
     * 搜索员工
     * @param key
     */
    public void search(String key) {
        items = new Items();
        for (Personnel personnel : personnelList) {
            if(personnel.getUsername().contains(key)){
                items.add(personnel);
            }
        }
        if(items.size() == 0){
            mContext.showNoData();
        }else{
            mContext.hideLoading();
            adapter.setItems(items);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 去除重复数据
     * @param list
     * @return
     */
    public List<Personnel> removeDuplicate(List<Personnel> list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }
}
